package lib.quasar.pedometer;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import static android.content.Context.ALARM_SERVICE;

/**
 * description: 计步初始化方法
 * created by kalu on 2018/4/3 14:24
 */
public final class PedometerManager {

    private static final String TAG = "PedometerManager";
    private static final int JOB_ID = 100;

    /**
     * 在程序的最开始调用，最好在自定义的application oncreate中调用
     */
    public static void init(Context context) {

        set0SeparateAlertManager(context);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            initJobScheduler(application);
        }


        startTodayStepService(context);
    }

    /**
     * 设置0点分隔Alert，当前天+1天的0点启动
     */
    private static final void set0SeparateAlertManager(Context context) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        String tomorrow = dateFormat(calendar.getTimeInMillis(), "yyyy-MM-dd");
        long timeInMillis = getDateMillis(tomorrow + " 00:00:00", "yyyy-MM-dd HH:mm:ss");

       //  LogUtil.e(TAG, DateUtil.dateFormat(timeInMillis, "yyyy-MM-dd HH:mm:ss"));

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        Intent i1 = new Intent(context, PedometerAlertReceive.class);
        i1.putExtra(PedometerService.INTENT_NAME_0_SEPARATE, true);
        i1.setAction(PedometerAlertReceive.ACTION_STEP_ALERT);
        PendingIntent operation = PendingIntent.getBroadcast(context, 0, i1, PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeInMillis, operation);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, operation);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, operation);
        }

    }

    public static void startTodayStepService(Context context) {
        Intent intent = new Intent(context, PedometerService.class);
        context.startService(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static void initJobScheduler(Application application) {
        Log.e(TAG, "initJobScheduler");

        JobScheduler jobScheduler = (JobScheduler)
                application.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder = new JobInfo.Builder(
                JOB_ID,
                new ComponentName(application.getPackageName(), PedometerJobService.class.getName()));
        builder.setMinimumLatency(5000)// 设置任务运行最少延迟时间
                .setOverrideDeadline(60000)// 设置deadline，若到期还没有达到规定的条件则会开始执行
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)// 设置网络条件
                .setRequiresCharging(true)// 设置是否充电的条件
                .setRequiresDeviceIdle(false);// 设置手机是否空闲的条件
        int resultCode = jobScheduler.schedule(builder.build());
        if (JobScheduler.RESULT_FAILURE == resultCode) {
            Log.e(TAG, "jobScheduler 失败");
        }
    }

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat();

    private static final String dateFormat(long millis, String pattern) {
        SIMPLE_DATE_FORMAT.applyPattern(pattern);
        Date date = new Date(millis);
        String dateString = SIMPLE_DATE_FORMAT.format(date);
        return dateString;
    }

    private static final long getDateMillis(String dateString, String pattern) {
        long millionSeconds = 0;
        SIMPLE_DATE_FORMAT.applyPattern(pattern);
        try {
            millionSeconds = SIMPLE_DATE_FORMAT.parse(dateString).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }// 毫秒

        return millionSeconds;
    }
}
